import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Modal,
  Row,
  Col,
  Button,
  Select,
  Input,
  Table,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;

const comulnsText = ['柜体', '货架', '地堆'];

interface SaveCabinetProps extends FormComponentProps {
  dispatch?: Dispatch | any;
  saveInfo?: any;
  logisList?: any;
  INITINFO?: any;
  visible: boolean;
  fetchAction: (typeName: string, payload: any) => void;
  changeVisible: (status: boolean) => void;
}

interface SaveCabinetState {
  searchValues: {
    logisId: number | string,
    name: string,
    code: string,
    pageIndex: number,
    pageSize: number,
  };
  typeNum: number;
  saveVisible: boolean;
  cabinetName: string;
  saveValues: {
    cabId: number | string,
    type: number | string,
    name: string,
  };
}

@connect(({
  partitionManagementCabinet: { saveInfo },
  common: { INITINFO },
}: any) => ({ saveInfo, INITINFO }))

class SaveCabinetElem extends Component<SaveCabinetProps, SaveCabinetState> {
  state: SaveCabinetState = {
    searchValues: {
      logisId: '',
      name: '',
      code: '',
      pageIndex: 1,
      pageSize: 5,
    },
    typeNum: 0,
    saveVisible: false,
    cabinetName: '',
    saveValues: {
      cabId: '',
      type: '',
      name: '',
    },
  }

  columns: any = () => {
    const { typeNum } = this.state;
    return ([
      {
        title: 'ID',
        dataIndex: 'id',
        align: 'center',
        width: 100,
      },
      {
        title: `${comulnsText[typeNum]}简称`,
        dataIndex: 'name',
        align: 'center',
      },
      {
        title: `${comulnsText[typeNum]}编号`,
        dataIndex: 'code',
        align: 'center',
        width: 200,
      },
      {
        title: '操作',
        align: 'center',
        width: 120,
        render: (val: any, record: any) => (
          <span
            className="operLink"
            onClick={() => this.handleShowSure(true, record)}
          >添加
          </span>
        ),
      },
    ]);
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { searchValues, typeNum } = this.state;
      const params = {
        type: typeNum,
        ...searchValues,
        ...values,
      };
      this.fetchAction('saveList', params);
    });
  }

  handleShowSure = (saveVisible: boolean, record?: any) => {
    const { typeNum } = this.state;
    this.setState({
      saveValues: {
        cabId: record ? record.id : '',
        type: record ? typeNum + 1 : '',
        name: record ? record.name : '',
      },
      saveVisible,
      cabinetName: record ? record.name : '',
    });
  }

  handleSubmit = () => {
    const { saveValues } = this.state;
    const { fetchAction } = this.props;
    fetchAction('saveCabs', saveValues);

    this.handleShowSure(false);
    this.handleCancel();
  }

  handleCancel = () => {
    const { changeVisible } = this.props;
    this.setState({
      searchValues: {
        logisId: '',
        name: '',
        code: '',
        pageIndex: 1,
        pageSize: 5,
      },
    }, () => changeVisible(false));
  }

  handleChangeType = (typeNum: number) => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const arg = {
      typeNum,
      searchValues: {
        logisId: '',
        name: '',
        code: '',
        pageIndex: 1,
        pageSize: 5,
      },
    };
    this.setState(arg, () => {
      const { form: { validateFields } } = this.props;
      validateFields((errors, values) => {
        if (errors) return;

        const params = { type: typeNum, ...values };
        this.fetchAction('saveList', params);
      });
    });
  }

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { searchValues } = this.state;
      const params = {
        ...searchValues,
        ...values,
        pageIndex,
        pageSize,
      };
      this.setState({ searchValues: params }, () => {
        this.fetchAction('saveList', params);
      });
    });
  }

  fetchAction = (typeName: string, payload = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: `partitionManagementCabinet/${typeName}`,
      payload,
    });
  }

  render() {
    const {
      searchValues: { pageIndex, pageSize },
      typeNum,
      saveVisible,
      cabinetName,
    } = this.state;
    const {
      form: { getFieldDecorator },
      visible,
      saveInfo,
      INITINFO: { logisList },
    } = this.props;
    const dataSource = saveInfo.list;

    const pagination: object = saveInfo
      ? {
        total: saveInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10'],
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    const typeName = `${comulnsText[typeNum]}名称`;
    const typeCode = `${comulnsText[typeNum]}编号`;

    return (
      <Fragment>
        <Modal
          title="添加柜体"
          width={800}
          destroyOnClose
          footer={null}
          visible={visible}
          onCancel={this.handleCancel}
        >
          <Form hideRequiredMark className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={8} sm={24}>
                <Form.Item label={typeName} colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入名称" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={8} sm={24}>
                <Form.Item label="　　类型" colon={false}>
                  {getFieldDecorator('type', ({
                    initialValue: 0,
                  }))(
                    <Select placeholder="请选择" onChange={this.handleChangeType}>
                      <Option value={0}>柜体</Option>
                      <Option value={1}>货架</Option>
                      <Option value={2}>地堆</Option>
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={8} sm={24}>
                <Form.Item label={typeCode} colon={false}>
                  {getFieldDecorator('code')(
                    <Input allowClear placeholder="请输入编号" />,
                  )}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={8} sm={24}>
                <Form.Item label="物流中心" colon={false}>
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(
                          input.toLowerCase(),
                        ) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={item.id} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={8} sm={24}> </Col>
              <Col md={8} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >查询
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
          <Table
            rowKey="id"
            className="tableList statementTable"
            style={{ marginTop: 24 }}
            columns={this.columns()}
            dataSource={dataSource}
            pagination={pagination}
          />
        </Modal>
        <Modal
          title="提示信息"
          visible={saveVisible}
          onOk={this.handleSubmit}
          onCancel={() => this.handleShowSure(false)}
        >
          <p>确定添加柜体{cabinetName}吗？</p>
        </Modal>
      </Fragment>
    );
  }
}

export default Form.create<SaveCabinetProps>()(SaveCabinetElem);
